package com.example.demo.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.entity.Business;
import com.example.demo.entity.Employee;
import com.example.demo.entity.LoginUser;
import com.example.demo.mapper.BusinessMapper;
import com.example.demo.mapper.EmployeeMapper;
import net.sf.jsqlparser.statement.grant.Grant;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.Permission;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    EmployeeMapper employeeMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
        //查询用户信息
        QueryWrapper<Employee> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("employee_name",username);
        Employee employee= employeeMapper.selectOne(queryWrapper);
        List<String> permissions=employeeMapper.selectPermissions(employee.getEmployeeId());
        String role=employeeMapper.selectRoleById(employee.getEmployeeId());
        //如果没有查询到用户则抛出异常
        if(Objects.isNull(employee))
        {
            throw new RuntimeException("用户名或者密码错误");
        }
        //组装权限
        Set<GrantedAuthority> authorities=new HashSet<>();
        for(String permission:permissions){
            authorities.add(new SimpleGrantedAuthority(permission));
        }
        return new LoginUser(employee.getEmployeeId(),employee.getEmployeeName(),employee.getEmployeePassword(),permissions,role, employee.getBusinessId());
    }
}
